Ext.define('BISC.view.ImagesPanel', {
    extend: 'Ext.panel.Panel',

    initComponent: function() {
        var me = this;

        Ext.applyIf(me, {
            tplBoth: new Ext.XTemplate(
            '<tpl for=".">' +
                '<div class="imageSel" style="position: relative; margin: auto; height: 150px; clear: both;">' +
                    '<img src="data:image/jpeg;base64,{thumbnail}" onerror="this.src=\'http://placehold.it/150x150&text=Generating Thumbnail\'" style="max-width: 150px; max-height: 150px; float: left;" alt="{path}">' +
                    '<div style="float: left;">' +
                        // image path
                        '<div style="margin: 10px;"><span style="font-weight: bold;">{path}</span></div>' +
                        // status icons
                        '<div style="padding: 5px; margin: 10px; top: 0px; right: 0px; position: absolute;">' +
                            // sync'd
                            '<tpl if="thumbnail != null"><img src="/resources/img/ico/synchronized.png" data-qtip="{timestampModified}" style="padding: 5px;"></tpl>' +
                            // not sync'd
                            '<tpl if="thumbnail == null"><img src="/resources/img/ico/unsynchronized.png" data-qtip="This image may be in the process queue." style="padding: 5px;"></tpl>' +
                            // blacklisted
                            '<tpl if="blackList == 1">' +
                                // error blacklisted
                                '<tpl if="error != \'\'">' +
                                    '<img src="/resources/img/ico/blacklisted.png" data-qtip="Cannot upload image to server. Does file extension match file type?" style="padding: 5px;">' +
                                    '<img src="/resources/img/ico/error.png" data-qtip="{error}" style="padding: 5px;">' +
                                '</tpl>' +
                                // user blacklisted
                                '<tpl if="error == \'\'"><img src="/resources/img/ico/blacklisted.png" data-qtip="Blacklisted images are not uploaded to the server." style="padding: 5px;"></tpl>' +
                            '</tpl>' +
                            // uploaded
                            '<tpl if="online == 1"><img src="/resources/img/ico/uploaded.png" data-qtip="{lastUploaded}" style="padding: 5px;"></tpl>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</tpl>'),
            tplSmall: new Ext.XTemplate(
                '<tpl for=".">'+
                '<div class="imageSel" style="width: 100px; height: 100px; display: inline-block;">' +
                    '<div>'+
                        '<img src="data:image/jpeg;base64,{thumbnail}" onerror="this.src=\'http://placehold.it/100x100&text=Generating Thumbnail\'" style="display: block; margin: auto; max-width: 100px; max-height: 100px;"" alt="{path}">' +
                    '</div>'+
                '</div>'+
                '</tpl>'
            ),
            tplLarge: new Ext.XTemplate(
                '<tpl for=".">'+
                '<div class="imageSel" style="display: inline-block;">' +
                    '<div style="padding: 5px;">'+
                        '<div>'+
                            '<span style="font-weight:bold">{path}</span><br/>{barcode} {family}<br/>{genus} {specificEpithet}'+
                        '</div>'+
                        '<div style="border-bottom: solid thin #9F9F9F; width: 275px; height: 276px;">'+
                            '<img src="data:image/jpeg;base64,{thumbnail}" onerror="this.src=\'http://placehold.it/275x276&text=Generating Thumbnail\'" style="display: block; margin: auto; max-width: 275px; max-height: 275px;" alt="{path}">' +
                        '</div>'+
                    '</div>'+
                '</div>'+
                '</tpl>'
            ),
            items: [
                {
                    xtype: 'dataview',
                    id: 'ImagesView',
                    overItemCls: 'imageHover',
                    selectedItemCls: 'imageSelect',
                    trackOver: true,
                    tpl: me.tplBoth,
                    autoScroll: true,
                    emptyText: '<div class=\'emptyText\'>No images available.</div>',
                    itemSelector: 'div.imageSel',
                    store: 'ImagesStore',
                    scope: me,
                    style: '-moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;',
                    selModel: {
                        mode: 'MULTI'
                    },
                    listeners: {
                        itemcontextmenu: me.onImagesViewItemContextMenu,
                        select: function( dataview, record, opts ) {
                            var bar = Ext.getCmp('imageDetailsBar');
                            bar.update( record.get('path') + ' - ' + record.get('timestampModified') );
                            bar.show();
                            Ext.data.JsonP.request({
                                url: 'http://localhost:8888/imageListAttributes',
                                params: {
                                    imageId: record.get('id'),
                                    bisId: Config.server.id
                                },
                                callback: function( success, data ) {
                                    Ext.getCmp('propertiesView').image = record.data;
                                    Ext.getCmp('propertiesView').update( data.records );
                                }
                            });
                        },
                        itemmouseenter: function( dataview, record, el, ind, e ) {
                            var store = Ext.StoreManager.lookup('FolderListStore');
                            var index = store.findExact('id', record.get('folderId'));
                            if ( index > -1 ) {
                                var elem = new Ext.Element( Ext.getCmp('monitorListDataview').getNode( index ) );
                                elem.addCls( 'hoverLightGreen' );
                            }
                        },
                        itemmouseleave: function( dataview, record, el, ind, e ) {
                            var store = Ext.StoreManager.lookup('FolderListStore');
                            var index = store.findExact('id', record.get('folderId'));
                            if ( index > -1 ) {
                                var elem = new Ext.Element( Ext.getCmp('monitorListDataview').getNode( index ) );
                                elem.removeCls( 'hoverLightGreen' );
                            }
                        },
                        deselect: function( dataview, record, opts ) {
                            if ( this.getSelectionModel().getSelection().length == 0 ) {
                                Ext.getCmp('propertiesView').update('<div style="padding:10px;">Select an image to view details.</div>');
                            }
                        }
                    }
                }
            ],
            dockedItems: [
                {
                    xtype: 'toolbar',
                    dock: 'top',
                    border: false,
                    items: [
                        {
                            xtype: 'cycle',
                            showText: true,
                            prependText: 'View ',
                            scope: me,
                            changeHandler: me.changeView,
                            menu: {
                                items: [{
                                    text: 'Both',
                                    iconCls: 'icon_viewBoth',
                                    type: 'tplBoth'
                                },{
                                    text: 'Small',
                                    iconCls: 'icon_viewSmall',
                                    type: 'tplSmall'
                                },{
                                    text: 'Large',
                                    iconCls: 'icon_viewLarge',
                                    type: 'tplLarge'
                                },{
                                    text: 'Details',
                                    iconCls: 'icon_viewList',
                                    disabled: true,
                                    type: 'details'
                                }]
                            }
                        },
                        {
                            xtype: 'button',
                            icon_class: 'icon_pictures',
                            text: 'View All',
                            scope: me,
                            handler: me.filterBy
                        },
                        '->',
                        {
                            xtype: 'textfield',
                            fieldLabel: 'Search',
                            labelWidth: 40,
                            scope: me,
                            enableKeyEvents: true,
                            listeners: {
                                scope: me,
                                keypress: function( field, e, opts ) {
                                    if ( e.keyCode == e.ENTER ) {
                                        this.filterBy({ filter: field.getValue() });
                                    }
                                }
                            }
                        }
                    ]
                },
                {
                    xtype: 'pagingtoolbar',
                    displayInfo: true,
                    store: 'ImagesStore',
                    displayMsg: 'Displaying {0} - {1} of {2}',
                    dock: 'bottom'
                }
            ]

        });
        me.callParent(arguments);
    },
    filterBy: function( filters ) {
        var params = { bisId: Config.server.id };
        if ( filters ) {
            params.filter = filters.filter;
        }
        Ext.StoreManager.lookup('ImagesStore').getProxy().extraParams = params;
        Ext.StoreManager.lookup('ImagesStore').load();
    },
	changeView: function( cycleBtn, item ) {
		if ( item.type != 'details' ) {
            Ext.getCmp('ImagesView').tpl = this[item.type];
            Ext.getCmp('ImagesView').refresh();
		}
	},
    onImagesViewItemContextMenu: function(dataview, record, item, index, e, options) {
        var selectedImages = Ext.pluck( Ext.pluck( dataview.getSelectionModel().getSelection(), 'data' ), 'id' );
        var uploadImage = function() {
            Ext.data.JsonP.request({
                url: 'http://localhost:8888/images/add',
                timeout: 120000,
                scope: this,
                params: {
                    'types[]': Ext.encode( { type: 'images', ids: selectedImages } ),
                    bisId: Config.server.id
                },
                success: function( responseObject ) {
                    if ( responseObject.success ) {
                        console.log('Uploaded');
                        // socket.io event will update
                    } else {
                        console.log('Not Uploaded');
                    }
                },
                failure: function() {
                    console.log('In Ajax failure function');
                }
            });
        };

        var deleteImage = function() {
            var obj = { type: 'images', ids: [ record.data.id ] };
            Ext.data.JsonP.request({
                url: 'http://localhost:8888/images/delete',
                timeout: 120000,
                scope: this,
                params: {
                    'types[]': obj,
                    bisId: 1 
                },
                success: function(responseObject) {
                    if ( responseObject.success ) {
                        console.log('Deleted');
                        // socket.io event will update
                    } else {
                        console.log('Not Deleted');
                    }
                },
                failure: function() {
                    console.log('In Ajax failure function');
                }
            });
        }

        var blacklistImage = function() {
            var blacklistGo = function() {
                Ext.Ajax.request({
                    url: 'http://localhost:8888/images/blacklist/' + record.data.id,
                    callback: function() { Ext.StoreManager.lookup('ImagesStore').load() }
                });
            }
            if ( record.data.online ) {
                Ext.Msg.confirm('Blacklist Uploaded Image', 'Blacklisting uploaded images will remove them from the configured image server. Are you sure you want to blacklist "' + record.data.path + '"?', function( btn, nothing, item ) {
                    if ( btn == 'yes' ) {
                        blacklistGo();
                        deleteImage();
                    }
                }, this); 
            } else {
                blacklistGo();
            }
        }

        var whitelistImage = function() {
            Ext.Ajax.request({
                url: 'http://localhost:8888/images/whitelist/' + record.data.id,
                callback: function() { Ext.StoreManager.lookup('ImagesStore').load() }
            });
        }

        var items = [];

        if ( record.data.blackList ) {
            items.push({
                text: 'Whitelist',
                iconCls: 'icon_whitelist',
                scope: this,
                handler: whitelistImage,
                stopEvent: true
            });
        } else {
            items.push({
                text: 'Blacklist',
                iconCls: 'icon_blacklist',
                scope: this,
                handler: blacklistImage,
                stopEvent: true
            });
        }

        if ( record.data.online ) {
            items.push({
                text: 'Pull from server',
                iconCls: 'icon_undo',
                scope: this,
                handler: deleteImage,
                stopEvent: true
            });
        } else if ( record.data.blackList == 0 ) {
            items.push({
                text: 'Upload to server',
                iconCls: 'icon_upload',
                scope: this,
                handler: uploadImage,
                stopEvent: true
            });
        }

        var contextMenu = new Ext.menu.Menu({
            items: items
        });

        contextMenu.showAt( e.getXY() );
        e.stopEvent();
    }

});
